package com.rsa.encrypt;

import com.rsa.common.RasCommon;
import com.rsa.tools.RsaTools;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.PublicKey;

/**
 * @author lf
 * @Description: 信息加密
 * @date 2020/7/30 12:27
 */
public class EncryptTools {

    private static final Logger log = LoggerFactory.getLogger(EncryptTools.class);

    /**
     * 信息加密
     * @param params    请求参数
     * @param pubKey    公钥
     * @return  密文
     */
    public static String dataEncrypt(String params, String pubKey) throws Exception {
        log.info("对外提供的信息加密方法...");
        return encrypt(params, RsaTools.getPublicKey(pubKey));
    }

    /**
     * RSA加密
     *
     * @param data 待加密数据
     * @param publicKey 公钥
     * @return
     */
    public static String encrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offset > 0) {
            if (inputLen - offset > RasCommon.MAX_ENCRYPT_BLOCK[0]) {
                cache = cipher.doFinal(data.getBytes(), offset, RasCommon.MAX_ENCRYPT_BLOCK[0]);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * RasCommon.MAX_ENCRYPT_BLOCK[0];
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
        // 加密后的字符串
        return new String(Base64.encodeBase64String(encryptedData));
    }
}
